# import socket
#
# # phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# # 1. 创建socket对象(买手机)
# phone = socket.socket() # 可以默认不写
#
# # 2. 绑定ip地址和端口(办卡)
# phone.bind(('127.0.0.1', 8848))  # 本地回环地址
#
# # 3. 监听.(开机状态)
# phone.listen(5)
#
# # 4. 接收连接
# print('start')
# conn, addr = phone.accept()  # 程序夯住
# # print(conn,addr)
# while 1:
#     from_client_data = conn.recv(1024)  #　至多接收1024个字节
#     print(f'来自客户端{addr}消息{from_client_data.decode("utf-8")}')
#     to_client = input('>>>')
#     conn.send(to_client.encode('utf-8'))
#
# conn.close()
# phone.close()

# 无论你的客户端是否正常关闭,服务端都应该正常关闭,而不是报错.


import socket

# phone = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 1. 创建socket对象(买手机)
phone = socket.socket() # 可以默认不写

# 2. 绑定ip地址和端口(办卡)
phone.bind(('127.0.0.1', 8888))  # 本地回环地址

# 3. 监听.(开机状态)
phone.listen(5)

# 4. 接收连接
print('start')
conn, addr = phone.accept()  # 程序夯住
# print(conn,addr)
while 1:
    try:
        from_client_data = conn.recv(1024)  #　至多接收1024个字节
        if from_client_data == b'q':
            break
        print(f'来自客户端{addr}消息{from_client_data.decode("utf-8")}')
        to_client = input('>>>')
        conn.send(to_client.encode('utf-8'))
    except ConnectionResetError:
        break
conn.close()
phone.close()

